package com.yxhl.zoume.core.tripsmgmt.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.FrameLayout;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.shareboard.SnsPlatform;
import com.umeng.socialize.utils.ShareBoardlistener;
import com.yxhl.protobuf.BizOrder;
import com.yxhl.protobuf.BizOrderResponse;
import com.yxhl.protobuf.OrderBizType;
import com.yxhl.zoume.R;
import com.yxhl.zoume.UIConstants;
import com.yxhl.zoume.common.ui.activity.base.BaseActivityWithToolBar;
import com.yxhl.zoume.core.func.push.model.PushMessage;
import com.yxhl.zoume.core.tripsmgmt.presenter.detail.DetailTripContainerPresenter;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail.DetailTripFragment;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail.ExpressCarTripDetailFragment;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail.OfficialCarTripDetailFragment;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail.SpecialCarTripDetailFragment;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail.TicketBusTripDetailFragment;
import com.yxhl.zoume.core.tripsmgmt.ui.fragment.tripsdetail.ZouMeBusTripDetailFragment;
import com.yxhl.zoume.core.tripsmgmt.view.detail.DetailOrderView;
import com.yxhl.zoume.di.component.trip.DaggerTripComponent;
import com.yxhl.zoume.di.module.ActivityModule;
import com.yxhl.zoume.di.module.trip.TripModule;
import com.yxhl.zoume.utils.LOG;
import com.yxhl.zoume.utils.PromptUtils;
import com.yxhl.zoume.utils.ZMDialog;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;

/**
 * Created by sugarya ; Email:sugarya@foxmail.com
 * 行程详情
 */
public class TripDetailContainerActivity extends BaseActivityWithToolBar implements DetailOrderView {

    public static final String SHARE_TEXT = "真实票源，查到即可买；定制巴士，随心出行；城际快车，接送到门。（目前各大应用商店已上架）";
    public static final String SHARE_TITLE = "车票随时买，快车接送到门";
    public static final String SHARE_TARGET_URL = "https://mp.weixin.qq.com/s?__biz=MzI2MjA3NTc0Nw==&mid=401246910&idx=1&sn=3d381b6df76510043ce1101f78543eb2&scene=1&srcid=0129j85PnFHIGfpUEjUUZQ03";
    private static final String TAG = "TripDetailContainerAct";
    @BindView(R.id.frame_activity_trip_detail_container)
    FrameLayout mFrameLayout;

    @Inject
    DetailTripContainerPresenter mDetailTripContainerPresenter;
    private BizOrder mBizOrder;
    private PushMessage mPushMessage;
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            PromptUtils.showShort(TripDetailContainerActivity.this, "分享成功");

        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            PromptUtils.showShort(TripDetailContainerActivity.this, "分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            PromptUtils.showShort(TripDetailContainerActivity.this, "分享取消");
        }
    };

    public static Intent getCallingIntent(Activity activity, BizOrder bizOrder) {
        Intent launch = new Intent(activity, TripDetailContainerActivity.class);
        if (bizOrder != null) {
            launch.putExtra(UIConstants.TripContainer.KEY_ORDER, bizOrder);
        }
        return launch;
    }

    public static Intent getCallingIntent(Activity activity, PushMessage pushMessage) {
        Intent launch = new Intent(activity, TripDetailContainerActivity.class);
        launch.putExtra(UIConstants.Push.INTENT_KEY_PUSH_INFO, pushMessage);
        return launch;
    }

    public static Intent getPushIntent(Context context, PushMessage pushMessage) {
        Intent launch = new Intent(context, TripDetailContainerActivity.class);
        launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        launch.putExtra(UIConstants.Push.INTENT_KEY_PUSH_INFO, pushMessage);
        return launch;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mDetailTripContainerPresenter.attachView(this);
        handleIntent();
        initializeShow();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mDetailTripContainerPresenter.attachView(this);
        setIntent(intent);
        handleIntent();
        initializeShow();
    }

    private void handleIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            mBizOrder = (BizOrder) intent.getSerializableExtra(UIConstants.TripContainer.KEY_ORDER);
            mPushMessage = (PushMessage) intent.getSerializableExtra(UIConstants.Push.INTENT_KEY_PUSH_INFO);
            LOG.e(TAG, "mPushMessage=" + mPushMessage);
        }
    }

    /**
     * 推送消息
     */
    private void initializeShow() {
        if (mBizOrder != null && mBizOrder.getId() != 0) {
            addFragment(R.id.frame_activity_trip_detail_container, fragmentProvider(mBizOrder));
        }
        //走消息推送
        else {
            if (mPushMessage != null) {
                //弹loading对话框
                ZMDialog.getLoadingDialog(this);
                mDetailTripContainerPresenter.getDetailTripOrder(mPushMessage.getId());
            }
        }
    }

    /**
     * 提供fragment
     *
     * @param bizOrder
     * @return
     */
    private Fragment fragmentProvider(BizOrder bizOrder) {
        Fragment fragment;
        OrderBizType bizType = bizOrder.getBizType();
        switch (bizType) {
            case OBT_DIY_BUS:
            case OBT_FT_BUS:
                fragment = ZouMeBusTripDetailFragment.newInstance(bizOrder);
                break;
            case TICKET:
            case OBT_DABA_TICKET:
                fragment = TicketBusTripDetailFragment.newInstance(bizOrder);
                break;
            case ORDER_BIZ_SHARE:
            case ORDER_BIZ_CHARTER:
                fragment = SpecialCarTripDetailFragment.newInstance(bizOrder);
                break;
            case OFFICIAL_BUS_TIME:
            case OFFICIAL_BUS_WAY:
                fragment = OfficialCarTripDetailFragment.newInstance(bizOrder);
                break;
            case SPECIAL_BUS_WAY:
            case SPECIAL_BUS_TIME:
                fragment = ExpressCarTripDetailFragment.newInstance(bizOrder);
                break;
            default:
                fragment = DetailTripFragment.newInstance(bizOrder);
        }
        return fragment;
    }

    /**
     * 分享到微信对话、朋友圈
     */
    private void shareToWechat() {
        final SHARE_MEDIA[] displayList = new SHARE_MEDIA[]{
                SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE};
        final UMImage image = new UMImage(this, BitmapFactory.decodeResource(getResources(), R.drawable.share_logo));

        new ShareAction(this).setDisplayList(displayList)
                .setShareboardclickCallback(new ShareBoardlistener() {
                    @Override
                    public void onclick(SnsPlatform snsPlatform, SHARE_MEDIA share_media) {
                        new ShareAction(TripDetailContainerActivity.this).setPlatform(share_media).setCallback(umShareListener)
                                .withTitle(SHARE_TITLE)
                                .withText(SHARE_TEXT)
                                .withMedia(image)
                                .withTargetUrl(SHARE_TARGET_URL)
                                .share();
                    }
                }).open();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    @Override
    public void renderDetailOrderOnSuccess(BizOrderResponse bizOrderResponse) {
        List<BizOrder> bizOrderList = bizOrderResponse.getOrderFieldsesList();
        if (bizOrderList != null && bizOrderList.size() > 0) {
            BizOrder bizOrder = bizOrderList.get(0);
            if (bizOrder != null && bizOrder.getId() != 0) {
                ZMDialog.getLoadingDialog(this).dismiss();
                addFragment(R.id.frame_activity_trip_detail_container, fragmentProvider(bizOrder));
            }
        }
    }

    @Override
    public void renderDetailOrderOnFailure() {
    }


    /**
     * 显示特定Tag的Fragment,如果是第一次显示,则新建并添加该Fragment
     *
     * @param fragmentTab
     */
    public void displayOneFragment(String fragmentTab, BizOrder bizOrder) {
        FragmentManager manager = getSupportFragmentManager();
        if (manager != null) {
            FragmentTransaction transaction = manager.beginTransaction();

            List<Fragment> fragments = manager.getFragments();
            if (fragments != null && fragments.size() > 0) {
                for (Fragment f : fragments) {
                    if (f != null) {
                        transaction.hide(f);
                    }
                }
            }

            Fragment fragmentByTag = manager.findFragmentByTag(fragmentTab);
            if (fragmentByTag != null) {
                transaction.show(fragmentByTag);
            } else {
                transaction.add(R.id.frame_activity_trip_detail_container, fragmentProvider(bizOrder), fragmentTab);
            }

            transaction.commitAllowingStateLoss();
        }
    }


    @Override
    protected void initializeInjector() {
        DaggerTripComponent.builder()
                .appComponent(getAppComponent())
                .activityModule(new ActivityModule(this))
                .tripModule(new TripModule())
                .build().inject(this);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_trips_detail_container;
    }

    @Override
    protected void onHeaderLeftClick(View view) {
        onBackPressed();
    }

    @Override
    protected void onHeaderRightClick(View view) {
        shareToWechat();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

}
